package com.lqwu.mallchatserver.common.thread;

import lombok.AllArgsConstructor;

import java.util.concurrent.ThreadFactory;

/**
 * 自定义线程工厂
 * 用于捕获线程异常
 */
@AllArgsConstructor
public class MyThreadFactory implements ThreadFactory {

    private static final GlobalUncaughtExceptionHandler HANDLER  = new GlobalUncaughtExceptionHandler();
    private ThreadFactory threadFactory;
    /**
     * 创建一个线程 (装饰器模式)
     * @param r a runnable to be executed by new thread instance
     * @return
     */
    @Override
    public Thread newThread(Runnable r) {
        // 调用原工厂创建线程
        Thread thread = threadFactory.newThread(r);
        // 设置自定义异常处理器
        thread.setUncaughtExceptionHandler(HANDLER);
        return thread;
    }
}
